<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box {
      width: 500px;
      margin: 0 auto;
      background-color: pink;
      border-radius: 10px;
    }

    input {
      position: relative;
      left: 50%;
      transform: translate(-50%);
      width: 100px;

    }

    .left {
      display: flex;
      height: 50px;
      line-height: 50px;
    }

    .right {
      display: flex;
      justify-content: flex-end;
      height: 50px;
      line-height: 50px;

    }
  </style>
</head>

<body>
  <div class="box">
    <input type="text">

  </div>
  <script>
    const input = document.querySelector('input')
    input.addEventListener('keyup', e => {
      if (e.key === 'Enter') {
        const txt = input.value.trim() || ''
        const div2 = document.createElement('div')
        div2.innerHTML = `<div class="right"><span>${input.value}</span></div>`
        document.querySelector('.box').appendChild(div2)
        input.value = ''
        const xhr = new XMLHttpRequest()
        xhr.open('get', 'http://ajax-api.itheima.net/api/robot?spoken=' + txt, true)
        xhr.send()
        xhr.addEventListener('load', () => {
          if (xhr.status >= 200 && xhr.readyState == 4) {
            const data = JSON.parse(xhr.responseText).data.info.text
            const div1 = document.createElement('div')
            div1.innerHTML = `<div class="left"><span>${data}</span></div>`
            document.querySelector('.box').appendChild(div1)
          } else {
            //失败
            alert('发送失败！！')
          }
        })
      }
    })

  </script>
</body>

</html>